package com.csthink.web.infrastructure.security.authentication.filter;

import com.csthink.common.application.ResponseWrapper;
import com.csthink.common.infrastructure.enums.ErrorEnum;
import com.csthink.web.infrastructure.security.AuthenticationHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.web.cors.CorsUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 升级版
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-12
 */
@Slf4j
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private final AuthenticationHelper authenticationHelper;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationHelper authenticationHelper) {
        super("/**");
        setAuthenticationManager(authenticationManager);
        this.authenticationHelper = authenticationHelper;
    }

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        return !CorsUtils.isPreFlightRequest(request);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        Authentication authentication = getAuthentication(request);
        return getAuthenticationManager().authenticate(authentication);
    }

    private Authentication getAuthentication(HttpServletRequest request) {
        return authenticationHelper.getParser(request).parseAuthentication(request);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authResult);
        chain.doFilter(request, response);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        SecurityContextHolder.clearContext();
        log.warn("{}", failed.getMessage(), failed);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        ResponseWrapper.responseError(ErrorEnum.UNAUTHORIZED, failed.getMessage(), response);
    }
}
